package com.sgb.capital.view.ui.activity;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.view.KeyEvent;
import android.view.View;

import com.sgb.capital.R;
import com.sgb.capital.base.BaseActivity;
import com.sgb.capital.callback.Constants;
import com.sgb.capital.callback.ZMessageEvent;
import com.sgb.capital.databinding.PaycounterActivityBinding;
import com.sgb.capital.utils.CryptoUtils;
import com.sgb.capital.utils.Utils;
import com.sgb.capital.view.pop.NewPayPop;
import com.sgb.capital.view.pop.PayTipPop;
import com.sgb.capital.view.pop.TipPop;
import com.sgb.capital.view.ui.adapter.PayCardAdapter;
import com.sgb.capital.view.widget.MToast;
import com.sgb.capital.viewmodel.CheckoutCounterModel;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.util.HashMap;
import java.util.Map;

import androidx.databinding.DataBindingUtil;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;

/**
 * 作者:张磊
 * 日期:2021/6/28 0028
 * 说明:充值中心
 */

public class PayCounterActivity extends BaseActivity implements NewPayPop.OnPopClickListener {

    private PaycounterActivityBinding mBinding;
    private PayCardAdapter mAdapter;

    Map<String, Object> map = new HashMap<>();
    private CheckoutCounterModel mModel;
    private NewPayPop mPayPop;
    private String mTradeNo;
    private String mMoney;
    private TipPop mTip;
    private PayTipPop mPayTipPop;
    private int mType = -1;
    private boolean mIsMain;
    private boolean mIsUser;

    public static void start(Context context, String money, String orderId, boolean isMain, boolean isUser) {
        Intent intent = new Intent(context, PayCounterActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
        intent.putExtra("money", money);
        intent.putExtra("orderId", orderId);
        intent.putExtra("isMain", isMain);
        intent.putExtra("isUser", isUser);
        context.startActivity(intent);
    }

    @Override
    protected void initView() {
        EventBus.getDefault().register(this);
        mBinding = DataBindingUtil.setContentView(this, R.layout.paycounter_activity);
        mTip = new TipPop(this, "温馨提示", "", null, "确定");
        mPayPop = new NewPayPop(PayCounterActivity.this, this);
        mPayTipPop = new PayTipPop(this);
        mPayTipPop.mTip1.setText("您已充值成功，请勿重复充值");
    }


    @Override
    public void initData() {
        mModel = new ViewModelProvider(this).get(CheckoutCounterModel.class);
        mMoney = getIntent().getStringExtra("money");
        mIsMain = getIntent().getBooleanExtra("isMain", false);
        mIsUser = getIntent().getBooleanExtra("isUser", false);
        mBinding.tvShow.setVisibility(mIsUser ? View.GONE : View.VISIBLE);
        mBinding.tvPrice.setText("￥" + mMoney);
        mPayPop.mPayPriceTv.setText("￥" + mMoney);
        mBinding.tvBtn.setText("确认充值 ￥" + mMoney);
        mBinding.rvCardList.setLayoutManager(new LinearLayoutManager(Utils.getContext()));
        mAdapter = new PayCardAdapter(this, null, position -> AddAndEditCardsActivity.start(PayCounterActivity.this, mAdapter.getDatas().get(position).id));
        mBinding.rvCardList.setAdapter(mAdapter);
        mModel.payInfo(this, getIntent().getStringExtra("orderId"));
        mModel.getQuick(this);
    }


    @Override
    public void initObserve() {
        // TODO: 2021/7/2 0002  银行卡列表
        mModel.mPayCardList.observe(this, payCardEntities -> {
            mAdapter.getDatas().clear();
            mAdapter.setDatas(payCardEntities);
        });
        mModel.mPayinfoentitymutablelivedata.observe(this, payInfoEntity -> mTradeNo = payInfoEntity.tradeNo);
    }

    @Override
    public void initListener() {
        mPayTipPop.mTvSure.setOnClickListener(v -> {
            mPayTipPop.dismiss();
            if (!mIsMain) {
                CapitalActivity.start(this, mIsUser);
            }
            finish();
        });
        mBinding.addNewCard.setOnClickListener(v -> startActivity(new Intent(this, AddAndEditCardsActivity.class)));
        mTip.mTvCancel.setOnClickListener(v -> {
            if (mTip.mTvCancel.getText().toString().contains("放弃") || mType == 0) {
                mTip.dismiss();
                finish();
            }
            mTip.dismiss();
        });
        mTip.mTvSure.setOnClickListener(v -> {
            mTip.dismiss();
        });
        mBinding.ivBack.setOnClickListener(v -> {
            mTip.initStr("您要放弃此次充值吗?", "继续充值", "放弃");
            mTip.show();
        });
        mPayTipPop.tvCall.setOnClickListener(v -> callPhone());
        mBinding.tvBtn.setOnClickListener(v -> {
            if (mAdapter.getSelectPosition() == -1) {
                MToast.showToast(Utils.getContext(), "请选择充值银行卡");
                return;
            }
            String phone = mAdapter.getDatas().get(mAdapter.getSelectPosition()).phone;
            String s = CryptoUtils.decryptAES_ECB(phone);
            mPayPop.mPhoneNumber.setText("请输入手机验证码(" + s.substring(0, 3) + "****" + s.substring(s.length() - 4) + ")");
            mPayPop.mClickListener.onClickNewGet();
        });

        mPayPop.mBackOrder.setOnClickListener(v -> {
            mPayPop.dismiss();
            if (!mIsMain) {
                CapitalActivity.start(this, mIsUser);
            }
            finish();
        });
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
        Utils.sendMsg(Constants.EVENT_REFRESH, null);
    }

    @Subscribe
    public void getCode(ZMessageEvent event) {
        switch (event.code) {
            case Constants
                    .EVENT_REFRESH:
                mModel.getQuick(this);
                break;
        }
    }

    @Override
    public void onClickNewGet() {
        map.put("amount", mMoney);
        map.put("gateId", mAdapter.getDatas().get(mAdapter.getSelectPosition()).gateId);
        map.put("payBandCardId", mAdapter.getDatas().get(mAdapter.getSelectPosition()).id);
        map.put("payType", "QP");
        map.put("tradeNo", mTradeNo);
        mModel.rechargeQuickPayOrderApply(this, map);
    }

    @Override
    public void onClickPayButton(String vCode) {
        map.put("verifyCode", vCode);
        mModel.rechargeQuickPayOrderConfirm(PayCounterActivity.this, map);
    }

    //显示验证码输入错误的弹框
    public void showErrorCode(int type, String tip) {
        mType = type;
        if (type == 0) {
            mTip.initStr(tip, null, "确定");
            mTip.show();
        } else if (type == 1) {
            mTip.initStr("银行卡信息错误，请重新核对信息", null, "确定");
            mTip.show();
        } else if (type == 2) {
            mPayPop.setTipText("验证码错误");
        } else if (type == 3) {
            mTip.initStr("充值失败，请重新充值", null, "确定");
            mTip.show();
            mPayPop.dismiss();
        } else if (type == 4) {
            mPayPop.mTip.setText(tip);
        } else if (type == 6) {
            mTip.initStr(tip, null, "确定");
            mTip.show();
            mPayPop.dismiss();
        } else {
            mPayTipPop.show();
        }
    }

    //重新请求验证码需要传上一次的返回值，merTrace
    public void setApplyCount(String s) {
        map.put("merTrace", s);
        mPayPop.show();
        mPayPop.setStartTimer();
    }

    public void callPhone() {
        Intent intent = new Intent(Intent.ACTION_DIAL);
        Uri data = Uri.parse("tel:" + "400-001-0051");
        intent.setData(data);
        startActivity(intent);
    }

    public void setConfirm() {
        mPayPop.mPayLayout.setVisibility(View.GONE);
        mPayPop.mPaySuccessLayout.setVisibility(View.VISIBLE);
    }


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }
}